package com.ruoyi.mobile.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class WxCode {
    private static WxCode instance;
    public static WxCode getInstance() {
        if (instance == null) {
            instance = new WxCode();
        }
        return instance;
    }

    public String getOpenId(String code, String appid, String secret) {
        String wxLoginUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
        String param = "appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
        String jsonString = GetPostUntil.sendGet(wxLoginUrl, param);
        JSONObject json = JSONObject.parseObject(jsonString);
        String openid = json.getString("openid");
        return openid;
    }

    public JSONObject wxDecrypt(String encryptedData, String iv, String sessionKey)
            throws NoSuchAlgorithmException,IllegalBlockSizeException,InvalidParameterSpecException,NoSuchProviderException,
            NoSuchPaddingException,InvalidKeyException,InvalidAlgorithmParameterException,BadPaddingException {
        // 加密秘钥
        byte[] keyByte = org.apache.commons.codec.binary.Base64.decodeBase64(sessionKey);
        // 偏移量
        byte[] ivByte = org.apache.commons.codec.binary.Base64.decodeBase64(iv);
        // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
        int base = 16;
        if (keyByte.length % base != 0) {
            int groups = keyByte.length / base + 1;
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
            keyByte = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
        parameters.init(new IvParameterSpec(ivByte));
        cipher.init(Cipher.DECRYPT_MODE, spec, parameters); // 初始化
        // 被加密的数据
        byte[] dataByte = org.apache.commons.codec.binary.Base64.decodeBase64(encryptedData);
        byte[] resultByte = cipher.doFinal(dataByte);
        if (null != resultByte && resultByte.length > 0) {
            String result = new String(resultByte, StandardCharsets.UTF_8);
            return JSONObject.parseObject(result);
        }else {
            return null;
        }
    }

    public String getMinPhonenumber(String encryptedData, String iv, String sessionKey) {
        JSONObject object = null;
        try {
            object = wxDecrypt(encryptedData, iv, sessionKey);
        }catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }catch (InvalidParameterSpecException e) {
            e.printStackTrace();
        }catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }catch (InvalidKeyException e) {
            e.printStackTrace();
        }catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }catch (NoSuchProviderException e) {
            e.printStackTrace();
        }catch (BadPaddingException e) {
            try {
                object = wxDecrypt(encryptedData, iv, sessionKey);
            }catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        Object number = object.get("phoneNumber");
        if (null != number) {
            return number.toString();
        }
        return null;
    }

    public com.alibaba.fastjson.JSONObject getMinOpenId(String code, String appid, String secret) {
        String wxLoginUrl = "https://api.weixin.qq.com/sns/jscode2session";
        String param = "appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
        String jsonString = GetPostUntil.sendGet(wxLoginUrl, param);
        JSONObject json = JSONObject.parseObject(jsonString);
        String openid = json.getString("openid");
        String sessionKey = json.getString("session_key");
        com.alibaba.fastjson.JSONObject result = new com.alibaba.fastjson.JSONObject();
        result.put("openid", openid);
        result.put("sessionKey", sessionKey);
        return result;
    }
}
